package com.aj.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.aj.activity.view.ImageControl;
import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.UserDao;
import com.aj.databases.entry.DigUserInfo;
import com.aj.databases.entry.PhotoInfo;
import com.aj.databases.entry.User;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.CMTRequest;
import com.aj.http.request.PhotoReportRequest;
import com.aj.http.request.PraiseRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.utils.PortraitLoaderUtil;

public class FamilyPhotoInfoActivity extends BaseActivity {
	private ArrayList<View> listViews = null;
	private ViewPager pager;
	private ViewPageAdapter adapter;
	private RelativeLayout bottom_tools;
	private Button share_to;
	private Button report_to;
	private CheckBox praise_to;
	private Button comment_to;
	private int count;
	private int allCount;
	private int index = 1;
	private User user;
	private UserDao userDao;
	private List<PhotoInfo> photoInfoList;
	private PhotoInfo commonPhotoInfo;
	private EditText enter_pray_edittext;
	private Button expressionbutton;
	private Button sendbutton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo_info);
		setActionBackgourdResource(R.drawable.photo_info_bar);
		ShareSDK.initSDK(this);
		initView();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ShareSDK.stopSDK(this);
	}

	class ButtonClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			PhotoInfo photoInfo = photoInfoList.get(pager.getCurrentItem());
			switch (v.getId()) {
			case R.id.share_to:
				showShare(photoInfo);
				break;
			case R.id.report_to:
				report(photoInfo);
				break;
			case R.id.comment_to:
				commont(photoInfo);
				break;
			default:
				break;
			}
		}
	}

	@Override
	protected void setMenuLayout(View view) {
		if (view != null && menu_leanlayout != null) {
			menu_leanlayout.addView(view, new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		}
	}

	public void commont(PhotoInfo photoInfo) {
		this.commonPhotoInfo = photoInfo;
		openPanel();
	}

	private void createMenu() {
		View view = LayoutInflater.from(FamilyPhotoInfoActivity.this).inflate(
				R.layout.menu_common_enter, null);
		// ClickEvent clickEvent = new ClickEvent();
		enter_pray_edittext = (EditText) view
				.findViewById(R.id.enter_pray_edittext);
		expressionbutton = (Button) view.findViewById(R.id.expressionbutton);
		sendbutton = (Button) view.findViewById(R.id.sendbutton);
		sendbutton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (enter_pray_edittext.getText().toString().trim().length() == 0) {
					Toast.makeText(FamilyPhotoInfoActivity.this, "请输入评论内容~",
							Toast.LENGTH_LONG).show();
					return;
				}
				showProgressDialog();
				new CMTRequest().excute(FamilyPhotoInfoActivity.this, user
						.getUser_id(), "1", null, "1", enter_pray_edittext
						.getText().toString(), commonPhotoInfo.getPhotoId(),
						null, user.getPhohe(), user.getPhohe(),
						new IHttpCallBack() {
							@Override
							public void success(String result) {
								try {
									closePanel();
									Common common = new Common(new JSONObject(
											result));
									if (common.getReturnCode() != null
											&& common
													.getReturnCode()
													.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
									}
									Toast.makeText(
											FamilyPhotoInfoActivity.this,
											common.getErrorMsg(),
											Toast.LENGTH_LONG).show();
								} catch (JSONException e) {
									e.printStackTrace();
								}
								dimissProgressDialog();
							}

							@Override
							public void fail(String result) {
								closePanel();
								dimissProgressDialog();
								Toast.makeText(FamilyPhotoInfoActivity.this,
										"网络异常", Toast.LENGTH_LONG).show();
							}
						});

			}
		});
		setMenuLayout(view);
	}

	private void praise(final boolean isChecked, final PhotoInfo photoInfo,
			final CompoundButton buttonView) {
		showProgressDialog();
		String oper = "0";
		if (isChecked) {
			oper = "0";
		} else {
			oper = "1";
		}
		new PraiseRequest().excute(FamilyPhotoInfoActivity.this,
				user.getUser_id(), photoInfo.getPhotoId(), oper,
				new IHttpCallBack() {
					@Override
					public void success(String result) {
						try {
							Common common = new Common(new JSONObject(result));
							if (common.getReturnCode() == null
									|| !common
											.getReturnCode()
											.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
								buttonView.setChecked(!isChecked);
							} else {
								List<DigUserInfo> digUserInfoList = photoInfo
										.getDigUserInfoList();
								if (isChecked) {
									if (digUserInfoList == null) {
										digUserInfoList = new ArrayList<DigUserInfo>();
									}
									DigUserInfo digUserInfo = new DigUserInfo();
									digUserInfo.setDig_user_id(user
											.getUser_id());
									digUserInfo.setDig_user_nick(user
											.getNickName() == null ? "" : user
											.getNickName());
									digUserInfoList.add(digUserInfo);
									photoInfo.setHadDig("1");
								} else {
									for (DigUserInfo digUserInfo : digUserInfoList) {
										if (digUserInfo.getDig_user_id()
												.equals(user.getUser_id())) {
											digUserInfoList.remove(digUserInfo);
											break;
										}
									}
									photoInfo.setHadDig("0");
								}
							}
							Toast.makeText(FamilyPhotoInfoActivity.this,
									common.getErrorMsg(), Toast.LENGTH_LONG)
									.show();
						} catch (JSONException e) {
							e.printStackTrace();
							Toast.makeText(FamilyPhotoInfoActivity.this,
									"网络异常", Toast.LENGTH_LONG).show();
							buttonView.setChecked(!isChecked);
						}
						dimissProgressDialog();

					}

					@Override
					public void fail(String result) {
						dimissProgressDialog();
						Toast.makeText(FamilyPhotoInfoActivity.this, "网络异常",
								Toast.LENGTH_LONG).show();
					}
				});

	}

	public void report(PhotoInfo photoInfo) {
		showProgressDialog();
		new PhotoReportRequest().excute(this, user.getUser_id(),
				photoInfo.getPhotoId(), new IHttpCallBack() {
					@Override
					public void success(String result) {
						try {
							Common common = new Common(new JSONObject(result));
							Toast.makeText(FamilyPhotoInfoActivity.this,
									common.getErrorMsg(), Toast.LENGTH_LONG)
									.show();
						} catch (JSONException e) {
							e.printStackTrace();
						}
						dimissProgressDialog();
					}

					@Override
					public void fail(String result) {
						dimissProgressDialog();
						Toast.makeText(FamilyPhotoInfoActivity.this, "网络异常",
								Toast.LENGTH_LONG).show();
					}
				});
	}

	private void showShare(PhotoInfo photoInfo) {
		OnekeyShare oks = new OnekeyShare();
		// 分享时Notification的图标和文字
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		oks.setTitle(getString(R.string.app_name));
		oks.setText("爱家APP，让你更快更便捷的了解家人动向~");
		oks.setImageUrl(photoInfo.getPhoto());
		// 启动分享GUI
		oks.show(this);
	}

	private void initView() {
		userDao = new UserDao(this);
		user = userDao.getCurrentUser(LoveHomeApplication.token);
		pager = (ViewPager) findViewById(R.id.viewpager);
		bottom_tools = (RelativeLayout) findViewById(R.id.bottom_tools);
		share_to = (Button) findViewById(R.id.share_to);
		report_to = (Button) findViewById(R.id.report_to);
		praise_to = (CheckBox) findViewById(R.id.praise_to);
		comment_to = (Button) findViewById(R.id.comment_to);
		ButtonClick buttonClick = new ButtonClick();
		share_to.setOnClickListener(buttonClick);
		report_to.setOnClickListener(buttonClick);
		comment_to.setOnClickListener(buttonClick);

		praise_to.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				PhotoInfo photoInfo = photoInfoList.get(pager.getCurrentItem());
				praise(praise_to.isChecked(), photoInfo, praise_to);
			}
		});

		pager.setOnPageChangeListener(pageChangeListener);
		index = getIntent().getIntExtra("index", 0);
		photoInfoList = (List<PhotoInfo>) getIntent().getSerializableExtra(
				"albumList");
		checkPraise(photoInfoList.get(index));
		if (photoInfoList != null && photoInfoList.size() > 0) {
			for (int i = 0; i < photoInfoList.size(); i++) {
				initListViews(photoInfoList.get(i));//
			}
			allCount = photoInfoList.size();
			setActionBarTitle((index + 1) + "/" + allCount);
			adapter = new ViewPageAdapter(listViews);// 构造adapter
			pager.setAdapter(adapter);
			pager.setCurrentItem(index);
		}
		createMenu();
	}

	private void initListViews(final PhotoInfo albumPhotoInfo) {
		if (listViews == null) {
			listViews = new ArrayList<View>();
		}
		final ImageControl imageControl = new ImageControl(
				FamilyPhotoInfoActivity.this);
		imageControl.setBackgroundColor(0xff000000);
		imageControl.post(new Runnable() {
			@Override
			public void run() {
				PortraitLoaderUtil.loadSrc(FamilyPhotoInfoActivity.this,
						imageControl, null, albumPhotoInfo.getPhoto(),
						R.drawable.nomal_photo, R.drawable.nomal_photo,
						imageControl.getMeasuredWidth(),
						imageControl.getMeasuredHeight());
			}
		});
		imageControl.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		listViews.add(imageControl);// 添加view
	}

	private void checkPraise(PhotoInfo photoInfo) {
		if (photoInfo.getHadDig().trim().equals("1")) {
			if (!praise_to.isChecked()) {
				praise_to.setChecked(true);
			}
		} else {
			if (praise_to.isChecked()) {
				praise_to.setChecked(false);
			}
		}
	}

	private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {// 页面选择响应函数
			count = arg0;
			setActionBarTitle((arg0 + 1) + "/" + allCount);
			checkPraise(photoInfoList.get(pager.getCurrentItem()));
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {// 滑动中。。。

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {// 滑动状态改变

		}
	};

	class ViewPageAdapter extends PagerAdapter {

		private ArrayList<View> listViews;// content

		private int size;// 页数

		public ViewPageAdapter(ArrayList<View> listViews) {// 构造函数
															// 初始化viewpager的时候给的一个页面
			this.listViews = listViews;
			size = listViews == null ? 0 : listViews.size();
		}

		public void setListViews(ArrayList<View> listViews) {// 自己写的一个方法用来添加数据
			this.listViews = listViews;
			size = listViews == null ? 0 : listViews.size();
		}

		@Override
		public int getCount() {// 返回数量
			return size;
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {// 销毁view对象
			((ViewPager) arg0).removeView(listViews.get(arg1 % size));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {// 返回view对象
			try {
				((ViewPager) arg0).addView(listViews.get(arg1 % size), 0);

			} catch (Exception e) {
			}
			return listViews.get(arg1 % size);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}
}
